import React from "react"

import http, { httpB } from "../helper/request"
import { TemplateType as TemplateItemType } from "./types"

export type { TemplateItemType }

export const setTemplateStatusRaw = (body: object | undefined) => http.post("/venue/redLimit/setShield", body)
export const syncTemplateRaw = (body: object | undefined) => http.post("/venue/redLimit/sync", body)

const useApi = () => {
	const { useState } = React
	const [loading, setLoading] = useState(false)
	async function generalHttp<T>(url: string, body: object | undefined) {
		setLoading(true)
		try {
			const ret = await http.post<T>(url, body)
			return ret
		} catch (error) {
			console.error("HTTP request failed", error)
			throw error
		} finally {
			setLoading(false)
		}
	}
	async function generalGet<T>(url: string, body: object | undefined) {
		setLoading(true)
		const ret = await http.get<T>(url, body)
		setLoading(false)
		return ret
	}

	// configB
	async function generalHttpB<T>(url: string, body: object | undefined) {
		setLoading(true)
		const ret = await httpB.post<T>(url, body)
		setLoading(false)
		return ret
	}

	async function generalGetB<T>(url: string, body: object | undefined) {
		setLoading(true)
		const ret = await httpB.get<T>(url, body)
		setLoading(false)
		return ret
	}
	const redTemplateList = async (body: object | undefined) => {
		const ret = generalHttp<{ pageNum: number; pageSize: number; record: TemplateItemType[]; totalRecord: number }>(
			"/venue/redLimit/templatePage",
			body
		)
		return ret
	}
	const setTemplateStatus = async (body: object | undefined) => {
		const ret = generalHttp("/venue/redLimit/setShield", body)
		return ret
	}

	const syncTemplate = async (body: object | undefined) => {
		const ret = generalHttp("/venue/redLimit/sync", body)
		return ret
	}
	const getImageUpload = async (url: string, body: object | undefined, header: any) => {
		setLoading(true)
		try {
			const ret = await http.post<any>(url, body, header)
			return ret
		} catch (error) {
			console.error("HTTP request failed", error)
			throw error
		} finally {
			setLoading(false)
		}
	}
	return {
		getImageUpload,
		redTemplateList,
		setTemplateStatus,
		syncTemplate,
		generalHttp,
		generalGet,
		generalGetB,
		generalHttpB,
		loading
	}
}

// export const redTemplateList = (body: object | undefined) =>
// 	http.post<{ record: TemplateItemType[] }>("/venue/redLimit/templatePage", body)

export default useApi
